import React, { useContext } from 'react';
import { Button, Row, Typography } from 'antd';
import { useRequest } from 'ahooks';
import CustomCard from '@/components/MarketingMap/CustomCard';
import DateFrom from '@/components/MarketingMap/DateFrom';
import PieChart from '@/components/MarketingMap/PieChart';
import BarChart from '@/components/MarketingMap/BarChart';
import { formatValue, sortByKey, content, isCategory } from '@/utils/marketingMap/utils';
import TabelLoadMore from '@/components/MarketingMap/TabelLoadMore';
import { fetchPersona, exportVehicle } from '@/services/marketingMap/activelyAnalyze';
import styles from '../styles/panel.less';
import OverallContext from '../context';
import TipMessage from '@/components/MarketingMap/TipMessage';
import BarEchart from '@/components/MarketingMap/BarEchart';

const StatisticsOverview: React.FC<any> = ({ map, markerClick, overviewData, rankData }) => {
  const { query, date, onSubmit } = useContext(OverallContext);
  // const { query } = useContext(OverallContext);

  const { data, loading } = useRequest(() => fetchPersona(query), {
    refreshDeps: [query],
  });
  const columns = [
    {
      title: '排名',
      dataIndex: 'rank',
      key: 'rank',
    },
    {
      title: <TipMessage name="活跃地">活跃地</TipMessage>,
      dataIndex: 'name',
      key: 'name',
      render: (text: string, _) => (
        <Typography.Text
          onClick={() => {
            if(!_.geoLon || ! _.geoLat) return
            map.setCenter([_.geoLon, _.geoLat], true);
            markerClick(content(_), [_.geoLon, _.geoLat]);
          }}
          style={{ width: 180, color: '#1890ff' }}
          ellipsis={{ tooltip: text }}
        >
          {text}
        </Typography.Text>
      ),
    },
    {
      title: <TipMessage name="活跃地保客数">活跃用户数</TipMessage>,
      dataIndex: 'vehicleCount',
    },
    {
      title: '最近专营店',
      dataIndex: 'nearestStoreName',
      render: (text: string) => (
        <Typography.Text style={{ width: 180 }} ellipsis={{ tooltip: text }}>
          {text}
        </Typography.Text>
      ),
    },
  ];

  return (
    <div className={styles.wrapper}>
      <div className={styles.level}>在哪外拓市场</div>

      <div className={styles.content}>
        <DateFrom value={date} onChange={onSubmit} isTag={false} />
        {/* <span>统计时间：{getDateRange(query.summaryDate)}</span> */}
        <div>
          <Typography className={styles.title}>
            <Typography.Text strong>活跃地数量</Typography.Text>
          </Typography>

          <div className={styles.box} style={{ padding: '0 24px' }}>
            <div className={styles.item}>
              <div>
                <span style={{ fontSize: 20, color: '#000' }}>
                  {formatValue(overviewData?.count)}
                </span>{' '}
                个
              </div>
              <span>活跃地数量</span>
            </div>
            <div className={styles.item}>
              <div>
                <span style={{ fontSize: 20, color: '#000' }}>
                  {formatValue(overviewData?.vehicleCount)}
                </span>{' '}
                台
              </div>
              <TipMessage name="活跃地保客数">
                <span>活跃用户数</span>
              </TipMessage>
            </div>
          </div>
        </div>

        <div>
          <Row justify="space-between" align="middle" className={styles.title}>
            <Typography.Text strong>活跃地排名</Typography.Text>
            <Button type="primary" onClick={() => exportVehicle(query)}>
              导出
            </Button>
          </Row>

          <TabelLoadMore
            columns={columns}
            loading={loading}
            dataSource={rankData || []}
            rowKey={(name: any, rank: any) => name + rank}
          />
        </div>

        <Typography className={styles.title} style={{ paddingBottom: 0 }}>
          <Typography.Text strong>整体用户画像</Typography.Text>
        </Typography>

        <CustomCard
          loading={loading}
          empty={!data?.[0]?.length}
          title={<Typography.Text strong>车系分布</Typography.Text>}
          extra={<Typography.Text style={{ fontSize: 12 }}>车辆（台）</Typography.Text>}
        >
          <PieChart
            name="车系分布"
            title="车辆总数"
            data={sortByKey(data?.[0], 'count')?.map(
              (item: { count: number; percent: string; name: string }) => ({
                value: item.count,
                percent: item.percent + '%',
                name: item.name,
              }),
            )}
          />
        </CustomCard>
        <CustomCard
          loading={loading}
          empty={!data?.[1]?.length}
          title={<Typography.Text strong>活跃地用户购车专营店分布</Typography.Text>}
          extra={<Typography.Text style={{ fontSize: 12 }}>车辆（台）</Typography.Text>}
        >
          <PieChart
            name="活跃地用户购车专营店分布"
            title="活跃用户数"
            rich={{
              b: {
                width: 80,
                align: 'right',
              },
              c: {
                width: 30,
                align: 'right',
              },
            }}
            data={sortByKey(data?.[1], 'count')?.map(
              (item: { count: number; percent: string; name: string }) => ({
                value: item.count,
                percent: item.percent + '%',
                name: item.name,
              }),
            )}
          />
        </CustomCard>
        <CustomCard
          loading={loading}
          empty={!data?.[2]?.length}
          title={<Typography.Text strong>活跃地与购车专营店距离分布</Typography.Text>}
        >
          <BarChart
            title="活跃地与购车专营店距离分布"
            name="车辆(台)"
            barGap={7}
            pl={10}
            data={data?.[2]?.map((item: { name: any; count: any }) => ({
              name: item.name,
              data: [item?.count || 0],
            }))}
          />
        </CustomCard>
        <CustomCard
          loading={loading}
          empty={!data?.[3]?.length}
          style={{ marginTop: 12 }}
          // title={<Typography.Text strong>活跃用户年龄分布</Typography.Text>}
          title={
            <Row align="bottom" style={{ gap: 6 }}>
              <Typography.Text strong>活跃用户年龄分布</Typography.Text>
              {isCategory(data?.[3]) && (
                <span style={{ fontSize: 12 }}>(无法判断性别年龄 {data[3][0].vins}人)</span>
              )}
            </Row>
          }
        >
          <BarEchart title="用户年龄分布" name="用户数（个）" data={data?.[3]} />
        </CustomCard>
      </div>
    </div>
  );
};

export default StatisticsOverview;
